import re

class HTMLTag(object):
    pass

class tag(HTMLTag):
    def __init__(self, __name, endTag=True, **kwargs):
        self.name = __name
        self.endTag = endTag
        self.attrs = {}
        for key, value in kwargs.items():
            newKey = key.replace("klass", "class")
            if kwargs[key] != None: self.attrs[newKey] = kwargs[key]
        self.content = []
        
    def getAttr(self, name):
        return self.attrs[name]
        
    def setAttr(self, name, value):
        self.attrs[name] = value
        
    def __getitem__(self, value):
        if isinstance(value, list) or isinstance(value, tuple):
            self.content = value
        else:
            self.content = [value]
        return self
        
    def __iadd__(self, value):
        if isinstance(value, list) or isinstance(value, tuple):
            self.content.extend(value)
        else:
            self.content.append(value)
        return self
        
    def mergeContent(self, content):
        result = []
        for item in content:
            if isinstance(item, tag):
                #result.extend(self.mergeContent(tag.content))
                result.append(str(item))
            else:
                #item = item.replace("\s*\n\s*\n\s*", "<p>\n")
                item = re.sub("\n\s*\n", "<p>", str(item))
                #item = re.sub("[ \v\f\t]+", " ", item)
                #item = item.strip()
                result.append(item)
                
        return " ".join(result)
        
    def __repr__(self):
        attrs = " ".join('%s="%s"' % (key, value) for key, value in self.attrs.items())
        if len(attrs) > 0: attrs = " " + attrs
        return "<%s%s>%s</%s>" % (self.name, attrs, self.mergeContent(self.content), self.name)
        #return "<%s%s>\n%s\n</%s>\n" % (self.name, attrs, " ".join(["\t%s" % e for e in self.content]), self.name)

class css(object):
    def __init__(self, env, name, **kwargs):
        if not name in env["doc.css"]:
            values = {}
            for key, value in kwargs.items():
                key = key.replace("_", "-")                
                values[key] = value
            env["doc.css"][name] = values